package com.hope.onlinestudy.activity.login

import android.text.TextUtils
import com.google.gson.Gson
import com.hope.onlinestudy.base.BaseDataModel
import com.hope.onlinestudy.model.LoginModel
import com.hope.onlinestudy.model.SystemConfigModel
import com.hope.onlinestudy.mvp.BasePresenterImpl
import com.hope.onlinestudy.net.HttpNetUtils
import com.hope.onlinestudy.net.NetworkScheduler
import com.hope.onlinestudy.net.ProgressSubscriber
import com.hope.onlinestudy.utils.ApiUtils
import com.hope.onlinestudy.utils.ApiUtils.loginModel
import com.hope.onlinestudy.utils.PreferencesUtils
import com.hope.onlinestudy.utils.Utils
import com.hope.onlinestudy.utils.Utils.parserJson
import me.jessyan.retrofiturlmanager.RetrofitUrlManager

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
class LoginPresenter :
    BasePresenterImpl<LoginContract.View>(),
    LoginContract.Presenter {
    override fun login(userName: String?, pass: String?) {
        if (TextUtils.isEmpty(userName)) {
            mView?.showMsg("用户名不能为空")
            return
        }
        if (TextUtils.isEmpty(pass)) {
            mView?.showMsg("登录密码不能为空")
            return
        }

        PreferencesUtils.putString(mView?.getMainContext()!!, "username", userName!!)
        PreferencesUtils.putString(mView?.getMainContext()!!, "userpwd", pass!!)

        val url =
            "${ApiUtils.configModel?.sys_base_url}${ApiUtils.configModel?.sys_h5_context}${ApiUtils.login}"
        val body = Gson().toJson(hashMapOf<String, Any>("username" to userName, "userpwd" to pass))
        HttpNetUtils.getInstance().getManager()?.login(url, body)
            ?.compose(NetworkScheduler.compose())
            ?.subscribe(object : ProgressSubscriber<LoginModel>(mView) {
                override fun onSuccess(data: LoginModel?, code: Int?) {
                    mView?.showMsg(data?.msg!!)
                    if (data?.statusCode == "0") {
                        loginModel = data
                        mView?.loginSuccess()
                    }
                }
            })
    }

    override fun getConfigSystem() {
        HttpNetUtils.getInstance().getManager()?.getConfig()?.compose(NetworkScheduler.compose())
            ?.subscribe(object :
                ProgressSubscriber<String>(mView, "配置加载中") {
                override fun onSuccess(data: String?, code: Int?) {
                    ApiUtils.configModel = parserJson<SystemConfigModel>(data!!)
                    RetrofitUrlManager.getInstance()
                        .putDomain("token", ApiUtils.configModel?.sys_base_url)
                }
            })
    }


}